<template>
  <div class="w-full mx-auto p-4 max-w-2xl">
    <h2 class="text-2xl font-bold mb-6">评论</h2>

    <CommentEditor v-if="showEditor" :reply-target="replyTarget" @submit="handleAddComment" @cancel="cancelReply" />
    <button v-else @click="startNewComment"
      class="w-full p-3 mb-6 text-left border border-gray-300 rounded-lg hover:bg-gray-50 text-gray-500">
      写下你的评论...
    </button>

    <div v-if="comments.length" class="space-y-4">
      <CommentItem v-for="comment in flatComments" :key="comment.id" :comment="comment" @reply="handleReplyClick"
        @delete="handleDelete" :ref="setCommentRef" />
    </div>
    <div v-else class="text-center py-8 text-gray-500">
      暂无评论，快来发表第一条评论吧！
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { Comment } from '~/types/comment'

definePageMeta({
  layout: 'minimal',
  showHeader: false
});

const showEditor = ref(false)
const comments = ref<Comment[]>([])
const replyTarget = ref<Comment | null>(null)
const commentRefs = ref<HTMLElement[]>([])

// 设置评论引用
const setCommentRef = (el: any) => {
  if (el) {
    commentRefs.value.push(el)
  }
}

// 扁平化评论结构
const flatComments = computed(() => {
  const flatten = (comments: Comment[], parent?: Comment): Comment[] => {
    return comments.flatMap(comment => {
      const flattened = {
        ...comment,
        parentAuthor: parent?.author.name,
        parentId: parent?.id
      }
      return [
        flattened,
        ...(comment.replies ? flatten(comment.replies, comment) : [])
      ]
    })
  }
  return flatten(comments.value)
})

// 模拟初始数据
onMounted(() => {
  comments.value = [
    {
      id: 1,
      content: '这是一条顶级评论',
      author: {
        name: '用户A',
        avatar: 'https://i.pravatar.cc/150?img=1'
      },
      createdAt: new Date(),
      replies: [
        {
          id: 3,
          content: '这是一条回复',
          author: {
            name: '用户B',
            avatar: 'https://i.pravatar.cc/150?img=2'
          },
          createdAt: new Date(),
          replies: [
            {
              id: 4,
              content: '这是嵌套回复',
              author: {
                name: '用户C',
                avatar: 'https://i.pravatar.cc/150?img=3'
              },
              createdAt: new Date()
            }
          ]
        }
      ]
    },
    {
      id: 2,
      content: '这是另一条顶级评论',
      author: {
        name: '用户D',
        avatar: 'https://i.pravatar.cc/150?img=4'
      },
      createdAt: new Date()
    }
  ]
})

// 开始新评论
const startNewComment = () => {
  replyTarget.value = null
  showEditor.value = true
}

// 处理添加评论
const handleAddComment = (content: string) => {
  const newComment: Comment = {
    id: Date.now(),
    content,
    author: {
      name: '当前用户',
      avatar: 'https://i.pravatar.cc/150?img=5'
    },
    createdAt: new Date()
  }

  if (replyTarget.value) {
    // 如果是回复，找到父评论并添加回复
    const addReply = (comments: Comment[]): boolean => {
      for (const comment of comments) {
        if (comment.id === replyTarget.value?.id) {
          if (!comment.replies) {
            comment.replies = []
          }
          comment.replies.unshift(newComment)
          return true
        }
        if (comment.replies && addReply(comment.replies)) {
          return true
        }
      }
      return false
    }
    addReply(comments.value)
  } else {
    // 否则添加为顶级评论
    comments.value.unshift(newComment)
  }

  cancelReply()
}

// 处理回复点击
const handleReplyClick = (comment: Comment) => {
  replyTarget.value = comment
  showEditor.value = true

  // 滚动到被回复的评论
  nextTick(() => {
    const targetElement = document.getElementById(`comment-${comment.id}`)
    if (targetElement) {
      targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
      targetElement.classList.add('bg-blue-50')
      setTimeout(() => {
        targetElement.classList.remove('bg-blue-50')
      }, 2000)
    }
  })
}

// 取消回复
const cancelReply = () => {
  replyTarget.value = null
  showEditor.value = false
}

// 删除评论
const handleDelete = (id: string | number) => {
  const deleteComment = (comments: Comment[]): Comment[] => {
    return comments.filter(comment => {
      if (comment.id === id) return false
      if (comment.replies) {
        comment.replies = deleteComment(comment.replies)
      }
      return true
    })
  }

  comments.value = deleteComment(comments.value)
}
</script>